#include "SimpleWindow.h"
namespace sw
{

HINSTANCE hinst = nullptr;
const TCHAR windowClassName[] = TEXT("simpleWindow");
void init(HINSTANCE hinst_)
{
	if (hinst_ == nullptr)
		throw 0;
	hinst = hinst_;
	registerWindowClass();
}
void registerWindowClass()
{
	WNDCLASS wndclass;
	wndclass.style = CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = SimpleWindow::WndProcSunk;
		//DefWindowProc;
	wndclass.cbClsExtra = 0;
	wndclass.cbWndExtra = 0;
	wndclass.hInstance = hinst;
	wndclass.hIcon = 0;
	wndclass.hCursor = NULL;
	wndclass.hbrBackground = NULL;
	wndclass.lpszMenuName = nullptr;
	wndclass.lpszClassName = windowClassName;
	if (!::RegisterClass(&wndclass))
		::exit(FALSE);
}
SimpleWindow::SimpleWindow(HWND parent)
{
	hwnd = CreateWindow(
		windowClassName,
		TEXT("simpleWindow"),
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT,
		CW_USEDEFAULT, CW_USEDEFAULT,
		parent, nullptr, hinst,this
	);
	SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)this);
}
void SimpleWindow::show(int nCmdShow) noexcept
{
	if (hwnd == nullptr)throw 0;
	ShowWindow(hwnd, nCmdShow);
}
void SimpleWindow::setText(std::wstring& str)
{
	SetWindowText(hwnd,str.c_str());
}
HWND SimpleWindow::getHandle()
{
	return hwnd;
}
bool SimpleWindow::getClientRect(RECT& rc)
{
	return GetClientRect(hwnd, &rc);
}
LRESULT SimpleWindow::WndProcSunk(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	SimpleWindow* pThis;
	if (msg == WM_NCCREATE || msg == WM_CREATE)
	{
		pThis = static_cast<SimpleWindow*>(reinterpret_cast<CREATESTRUCT*>(lParam)->lpCreateParams);

		SetLastError(0);
		if (!SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(pThis)))
		{
			if (GetLastError() != 0)
				return FALSE;
		}
	}
	else
	{
		pThis = reinterpret_cast<SimpleWindow*>(GetWindowLongPtr(hwnd, GWLP_USERDATA));
	}

	if (pThis)
	{
		return pThis->WndProc(hwnd, msg, wParam, lParam);
	}

	return DefWindowProc(hwnd, msg, wParam, lParam);
}
LRESULT SimpleWindow::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	return DefWindowProc(hwnd, msg, wParam, lParam);
}
}